package com.zhkj.txg.module.cart.ui

import android.view.View
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.scale
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.entity.node.BaseNode
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.cart.adapter.CartAdapter
import com.zhkj.txg.module.cart.adapter.CartHotAdapter
import com.zhkj.txg.module.cart.adapter.OnCartItemSelectedListener
import com.zhkj.txg.module.cart.entity.CartProductEntity
import com.zhkj.txg.module.cart.vm.CartViewModel
import com.zhkj.txg.module.order.ui.OrderSubmitActivity
import com.zhkj.txg.module.product.ui.ProductDetailActivity
import com.zhkj.txg.utils.GridItemDecoration
import kotlinx.android.synthetic.main.fragment_cart.*
import kotlinx.android.synthetic.main.fragment_home.*

class CartFragment : ViewModelFragment<CartViewModel>() {

    override fun setViewModel(): CartViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_cart

    private val listener = object : OnCartItemSelectedListener {
        // 选中状态发生变化
        override fun changed() {
            refreshStatusAndPrice()
        }

        // 数量变化
        override fun numberChange(uiPosition: Int, type: Int, originNumber: Int, maxCount: Int) {
            setCartNumber(uiPosition, type, originNumber, maxCount)
            refreshStatusAndPrice()
        }

        // 删除购物车item
        override fun itemDelete(uiPosition: Int) {
            showConfirmPopupWindow(uiPosition)
        }

        override fun itemClick(uiPosition: Int, product: CartProductEntity) {
            if (mode == 0) {
                if (product.isGoodsOnSale()) ProductDetailActivity.normalProduct(
                    requireContext(),
                    product.goodsId,
                    true
                )
            } else {
                (cartAdapter.data[uiPosition] as? CartProductEntity)?.selected =
                    (cartAdapter.data[uiPosition] as? CartProductEntity)?.selected?.not() ?: false
                refreshStatusAndPrice(true)
            }
        }
    }

    // 购物车Adapter
    private val cartAdapter: CartAdapter by lazy { CartAdapter(listener) }

    // 热门商品Adapter
    private val productAdapter = CartHotAdapter().apply {
        loadMoreModule?.isEnableLoadMore = true
        headerWithEmptyEnable = true
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.getProducts(AccountManager.getToken())
        }
        setOnItemClickListener { _, _, position ->
            ProductDetailActivity.normalProduct(requireActivity(), data[position].id, true)
        }
    }

    /**
     * 0 - 结算模式,1 - 编辑模式
     */
    private var mode = 0

    private var refresh = false
    private var refreshAll = false

    override fun initUI() {
        // 设置状态栏高度、编辑按钮点击事件
        titleCart.setFragmentStatusBar()
        titleCart.setRightClickListener(View.OnClickListener {
            mode = if (mode == 0) 1 else 0
            refreshModeStatus()
        })
        // 设置热卖商品Adapter
        with(rvCartProduct) {
            layoutManager = GridLayoutManager(activity, 2).apply {
                spanSizeLookup.isSpanIndexCacheEnabled = true
            }
            addItemDecoration(
                GridItemDecoration(
                    ScreenUtil.dip(requireContext(), 20),
                    ScreenUtil.dip(requireContext(), 10)
                )
            )
            adapter = productAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                val llm = layoutManager as GridLayoutManager
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    val firstItem = llm.findFirstVisibleItemPosition()
                    ivCartTop.visibility = if (firstItem > 20) View.VISIBLE else View.GONE
                }
            })
        }
        with(productAdapter) {
            setEmptyView(R.layout.layout_empty_data)
            setHeaderView(createHeaderView())
        }
        // 全选按钮点击监听
        cbCartAll.setOnCheckedChangeListener { buttonView, isChecked ->
            if (buttonView.isPressed) {
                cartAdapter.refreshStatusEntity(true, isChecked,ignoreOnSale = mode == 1)
                refreshStatusAndPrice()
            }
        }
        // 结算按钮点击监听
        tvCartBuy.setOnClickListener {
            val cartIds = cartAdapter.getCartIds()
            OrderSubmitActivity.cartBuy(requireContext(), cartIds)
        }
        // 删除按钮点击监听
        tvCartDelete.setOnClickListener {
            val cartIds = cartAdapter.getCartIds()
            viewModel.deleteCart(AccountManager.getToken(), cartIds)
        }
        // 滚动到顶部
        ivCartTop.setOnClickListener {
            rvCartProduct.scrollToPosition(0)
        }
        refreshCart.setOnRefreshListener {
            mode = 0
            refreshModeStatus()
            initData()
        }
    }

    @Suppress("UNCHECKED_CAST")
    override fun initViewModel() {
        // 购物车商品观察者
        viewModel.cartLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                response.response?.data?.let {
                    // 数据填充
                    cartAdapter.setNewData(it.cartList as? MutableList<BaseNode>)
//                    tvCartTotal.text = SpanUtil.setPrefixMoneyStr("合计:", it.totalPrice)
                    tvCartTotal.text = buildSpannedString {
                        append("合计:￥").bold { scale(1.2F) { append(it.totalPrice) } }
                    }
                    refreshStatusAndPrice()
                }
            } else if (response.status == HttpResponseStatus.Status.FAILURE) refreshCart.finishRefresh(false)
        })
        // 热门商品数据观察者
//        viewModel.hotGoodsLiveData.observe(viewLifecycleOwner, Observer { data ->
//            when (data.status) {
//                HttpResponseStatus.Status.START -> Unit
//                HttpResponseStatus.Status.SUCCESS -> data.response?.let {
//                    // 恢复加载状态
//                    if (!it.loadMore) refreshCart.finishRefresh()
//                    else if (it.hasMore) productAdapter.loadMoreModule?.loadMoreComplete()
//                    else productAdapter.loadMoreModule?.loadMoreEnd()
//                    // 填充数据
//                    if (it.loadMore) productAdapter.addData(it.data)
//                    else productAdapter.setNewData(it.data)
//                }
//                HttpResponseStatus.Status.FAILURE -> {
//                    data.exception?.printStackTrace()
//                    toast(data.statusTip)
//                    if (viewModel.page > 1) productAdapter.loadMoreModule?.loadMoreFail()
//                    else refreshHome.finishRefresh(false)
//                }
//            }
//        })
        // 购物车商品数量改变观察者
        viewModel.changeNumberLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                cartAdapter.refreshStatusEntity(cartId = it.cartId, number = it.currentNumber,ignoreOnSale = mode == 1)
                refreshStatusAndPrice()
            } else if (response.status == HttpResponseStatus.Status.FAILURE) cartAdapter.notifyDataSetChanged()
        })
        // 购物车商品删除观察者
        viewModel.deleteCartLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                mode = 0
                refreshModeStatus()
                viewModel.getCart(AccountManager.getToken(), false)
            }
        })
        // 购物车商品刷新观察者
        viewModel.cartChangeSubscribe().observe(viewLifecycleOwner, Observer { refresh = true })
        // 切换账户观察者
        viewModel.accountChangeSubscribe().observe(viewLifecycleOwner, Observer { refreshAll = true })
        // 会员状态观察者
        viewModel.memberStatusChangeSubscribe().observe(viewLifecycleOwner, Observer { refreshAll = true })
    }

    override fun initData() {
        // 获取购物车参数
        viewModel.getCart(AccountManager.getToken(), true)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden && refreshAll) {
            rvCartProduct.scrollToPosition(0)
            viewModel.getCart(AccountManager.getToken(), true)
            refreshAll = false
            refresh = false
        }
        if (!hidden && refresh) {
            rvCartProduct.scrollToPosition(0)
            refresh = false
            viewModel.getCart(AccountManager.getToken(), false)
        }
    }

    override fun onResume() {
        super.onResume()
        if (refreshAll) {
            rvCartProduct.scrollToPosition(0)
            viewModel.getCart(AccountManager.getToken(), true)
            refreshAll = false
            refresh = false
        }
        if (refresh) {
            rvCartProduct.scrollToPosition(0)
            refresh = false
            viewModel.getCart(AccountManager.getToken(), false)
        }
    }

    private fun refreshModeStatus() {
        titleCart.setRightTextContent(getString(if (mode == 0) R.string.edit else R.string.done))
        tvCartTotal.visibility = if (mode == 0) View.VISIBLE else View.INVISIBLE
        tvCartDelete.visibility = if (mode == 0) View.GONE else View.VISIBLE
        tvCartBuy.visibility = if (mode == 0) View.VISIBLE else View.GONE
    }

    /**
     * 刷新选中状态以及总价
     */
    private fun refreshStatusAndPrice(refresh: Boolean = false) {
        if (refresh) cartAdapter.notifyDataSetChanged()
        cartAdapter.refreshStatusEntity(ignoreOnSale = mode == 1)
//        tvCartTotal.text = SpanUtil.setPrefixMoneyStr("合计:", cartAdapter.checkStatusEntity.totalPrice)
        tvCartTotal.text = buildSpannedString {
            append("合计:￥").bold { scale(1.2F) { append(cartAdapter.checkStatusEntity.totalPrice) } }
        }
        cbCartAll.isChecked = cartAdapter.checkStatusEntity.allSelected
        tvCartBuy.isEnabled = cartAdapter.checkStatusEntity.selectAny
        tvCartDelete.isEnabled = cartAdapter.checkStatusEntity.selectAny
    }

    /**
     * 设置商品数量,并刷新价格
     */
    private fun setCartNumber(uiPosition: Int, type: Int, originNumber: Int, maxStock: Int) {
        (cartAdapter.data[uiPosition] as? CartProductEntity)?.let {
            if (originNumber > maxStock) {
                toast(getString(R.string.more_than_stock))
                return
            }
            if (originNumber <= 0) {
                toast(getString(R.string.product_number_change))
                return
            }
            when (type) {
                0 -> viewModel.changeCartNumber(
                    AccountManager.getToken(),
                    it.cartId,
                    originNumber - 1
                )
                1 -> viewModel.changeCartNumber(
                    AccountManager.getToken(),
                    it.cartId,
                    originNumber + 1
                )
                else -> viewModel.changeCartNumber(AccountManager.getToken(), it.cartId, originNumber)
            }
        }
    }

    private fun createHeaderView(): View {
        return layoutInflater.inflate(R.layout.item_cart_top, null).apply {
            // 设置购物车商品Adapter
            with(findViewById<RecyclerView>(R.id.rvCart)) {
                layoutManager = LinearLayoutManager(activity)
                adapter = cartAdapter
                (itemAnimator as? DefaultItemAnimator)?.supportsChangeAnimations = false
            }
            cartAdapter.setEmptyView(R.layout.layout_empty_data)
        }
    }

    private fun showConfirmPopupWindow(uiPosition: Int) {
        (cartAdapter.data[uiPosition] as? CartProductEntity)?.let {
            viewModel.deleteCart(AccountManager.getToken(), it.cartId.toString())
        }
    }
}